<?php
include_once('config/config.php');

// 判断是否登录函数
$LoginAdmin = checkAuth();

$id = $_GET['id'] ?? 0;

$presonSql = "SELECT * FROM `pre_person` WHERE `id` = '$id'";
$preson = find($presonSql);


if (empty($preson)) {
    showMsg('该员工不存在');
}

// 查询部门数据
$DepSql = "SELECT * FROM `pre_department` ORDER BY `id` ASC";
$DepData = findAll($DepSql);
// print_r($preson);
// echo $preson['depid'];
// print_r($DepData);
// foreach($DepData as $item){

// }
// exit;
// 获取员工id
$depid = $preson['depid'] ?? '';


// 查询对应的员工数据
$jobSql = "SELECT * FROM `pre_job` WHERE `depid` = '$depid'";

$jobData = findAll($jobSql);

if ($_POST) {
    $name = $_POST['name'] ?? '';
    $mobile = $_POST['mobile'] ?? '';
    $email = $_POST['email'] ?? '';
    $sex = $_POST['sex'] ?? '保密';
    $address = $_POST['address'] ?? '';
    $depid = $_POST['depid'] ?? '0';
    $jobid = $_POST['jobid'] ?? '0';

    if (empty($name) || empty($mobile) || empty($email) || empty($address) || empty($depid) || empty($jobid)) {
        showMsg('请填写完整信息');
    }

    // 判断手机号格式
    $mobileReg = "/^1[3456789]\d{9}$/";

    // 将匹配成功的值 => $mobileRes 
    preg_match($mobileReg, $mobile, $mobileRes);

    // 假设没有匹配成功
    if (empty($mobileRes)) {
        showMsg('手机号格式不正确');
    }

    // 存储原手机号
    $presonModel = $preson['mobile'] ?? '';

    echo $presonModel;
    $mobileSql = "SELECT `mobile` FROM `pre_person` WHERE `mobile` != '$presonModel'";

    // 将除原手机号的值全查出来
    $mobileData = findAll($mobileSql);
    
    // 判断手机号是否重复 false 不重复 true 重复
    $mobileFlag = false;

    foreach ($mobileData as $item) {
        // 将输入的手机号与数据库中已有的手机号进行匹配
        if ($item['mobile'] == $mobile) {
            // 如重复
            $mobileFlag = true;
            break;
        }
    }

    if ($mobileFlag) {
        showMsg('手机号已存在');
    }

    // 邮箱正则
    // $emailReg = "/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/";

    $presonEmail = $preson['email'] ?? '';

    $emailSql = "SELECT `email` FROM `pre_person` WHERE `email` != '$presonEmail'";

    $emailData = findAll($emailSql);

    $emailFlag = false;

    foreach ($emailData as $item) {
        if ($item['email'] == $email) {
            $emailFlag = true;
            break;
        }
    }

    if ($emailFlag) {
        showMsg('邮箱已存在');
    }

    // 封装数据
    $data = [
        'name' => $name,
        'mobile' => $mobile,
        'sex' => $sex,
        'email' => $email,
        'address' => $address,
        'depid' => $depid,
        'jobid' => $jobid
    ];

    // 处理地区逻辑
    $code = $_POST['code'] ?? '';

    $regionSql = "SELECT `parentpath` FROM `pre_region` WHERE `code` = '$code'";
    $regionData = find($regionSql);

    if (!$regionData) {
        showMsg('地区不存在');
    }

    // 将字符串转数组
    $path = explode(',', $regionData['parentpath']);

    // 把省市区追加到data数组里
    $data['province'] = $path[0] ?? null;
    $data['city'] = $path[1] ?? null;
    $data['district'] = $path[2] ?? null;


    // 判断是否有文件上传，没有就不执行下去
    // if ($_FILES['avatar']['error'] == 0) {
    //     // 执行文件上传
    //     // 处理上传头像
    //     $res = build_upload('avatar');

    //     if ($res['code'] == 0) {
    //         showMsg($res['msg']);
    //     }
    //     // 判断头像是否修改
    //     if ($res['data'] != $preson['avatar']) {
    //         // 删除旧头像文件
    //         $url = '.' . $preson['avatar'];
    //         unlink($url);
    //         $avatar =  $res['data'] ?? null;
    //     }
    // };
    // 处理头像逻辑
    if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
        $res = build_upload('avatar');

        if ($res['code'] === 0) {
            showMsg($res['msg']);
        } else {
            // 将新头像封装
            $data['avatar'] = $res['data'];
            // 删除旧头像
            $url = '.' . $preson['avatar'];
            unlink($url);
        }
    }



    // 添加数据并且把添加的时间加进去
    $data['createtime'] = time();

    $result = upd('person', $data, $id);

    if ($result['code'] === 1) {
        showMsg('更新成功', 'presonList.php');
    } else {
        @is_file('.' . $data['avatar']) && @unlink('.' . $data['avatar']);
        echo $result['data'];
        exit;
    }
}


?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include_once('common/meta.php'); ?>
    <link rel="stylesheet" href="/assets/lib/city-picker/city-picker.css">
</head>
<style>
    .region {
        position: relative;
        width: 530px;
    }

    .address {
        margin-top: 50px;
    }
</style>

<body>

    <?php include_once('common/header.php'); ?>

    <?php include_once('common/menu.php'); ?>

    <div class="content">
        <div class="header">
            <h1 class="page-title">编辑用户</h1>
        </div>
        <ul class="breadcrumb">
            <li><a href="presonList.php">presonList</a> <span class="divider">/</span></li>
            <li class="active">presonAdd</li>
        </ul>

        <div class="container-fluid">
            <div class="row-fluid">

                <div class="btn-toolbar">
                    <button class="btn btn-primary" onClick="location='presonList.php'"><i class="icon-list"></i> 管理员列表</button>
                    <div class="btn-group">
                    </div>
                </div>

                <div class="well">
                    <div id="myTabContent" class="tab-content">
                        <div class="tab-pane active in" id="home">
                            <form method="post" enctype="multipart/form-data">

                                <label>员工姓名</label>
                                <input type="text" name="name" placeholder="请输入员工姓名" id="name" required class="input-xxlarge" value="<?php echo $preson['name']; ?>">

                                <label>手机号</label>
                                <input type="text" name="mobile" placeholder="请输入手机号" id="mobile" required class="input-xxlarge" value="<?php echo $preson['mobile']; ?>">

                                <label>邮箱</label>
                                <input type="email" name="email" placeholder="请输入邮箱" id="email" required class="input-xxlarge" value="<?php echo $preson['email']; ?>">

                                <label>性别</label>
                                <select name="sex" id="sex" class="input-xlarge">
                                    <option value="保密" <?php echo $preson['sex'] == '保密' ? 'selected' : '' ?>>保密</option>
                                    <option value="男" <?php echo $preson['sex'] == '男' ? 'selected' : '' ?>>男</option>
                                    <option value="女" <?php echo $preson['sex'] == '女' ? 'selected' : '' ?>>女</option>
                                </select>

                                <div class="form-group region">
                                    <label for="region">选择地区</label>
                                    <input type="text" id="region" data-toggle="city-picker" value="<?php echo $preson['district'] ? $preson['district'] : ($preson['city'] ? $preson['city'] : $preson['province']) ?>" readonly class="input-xxlarge">
                                    <input type="hidden" name="code" id="code" value="<?php echo $preson['district'] ? $preson['district'] : ($preson['city'] ? $preson['city'] : $preson['province']) ?>">
                                </div>

                                <div class="address">
                                    <label>详细地址</label>
                                    <input type="text" name="address" id="address" placeholder="请输入详细地址" required value="<?php echo $preson['address']; ?>" class="input-xxlarge">
                                </div>

                                <label>部门</label>
                                <select name="depid" id="depid" class="input-xlarge">
                                    <option value="">请选择</option>
                                    <?php foreach ($DepData as $item) { ?>
                                        <option value="<?php echo $item['id']; ?>" <?php echo $item['id'] == $preson['depid'] ? 'selected' : ''; ?>><?php echo $item['name']; ?></option>

                                    <?php } ?>
                                </select>

                                <label>职位</label>
                                <select name="jobid" id="jobid" class="input-xlarge">
                                    <option value="">请选择</option>
                                    <?php foreach ($jobData as $item) { ?>
                                        <option value="<?php echo $item['id']; ?>" <?php echo $preson['jobid'] == $item['id'] ? 'selected' . '' : ''; ?>>
                                            <?php echo $item['name']; ?></option>
                                    <?php } ?>
                                </select>


                                <!-- <label>头像</label>
                                <input type="file" name="avatar" id="avatar" hidden class="input-xxlarge">
                                <img src="/assets/images/upload.png" style="width: 200px;height:200px" id="img" alt=""> -->

                                <label>头像</label>
                                <input type="file" name="avatar" id="avatar" hidden class="input-xxlarge">
                                <img src="<?php echo @is_file("." . $preson['avatar']) ? $preson['avatar'] : '/assets/images/avatar.png' ?>" style="width: 200px;height:200px" id="img" alt="">


                                <label></label>
                                <input class="btn btn-primary" type="submit" id="submit" value="提交" />
                            </form>
                        </div>
                    </div>
                </div>

                <?php include_once('common/footer.php'); ?>

            </div>
        </div>
    </div>

</body>

</html>

<?php include_once('common/script.php'); ?>
<script src="/assets/lib/city-picker/city-picker.data.min.js"></script>
<script src="/assets/lib/city-picker/city-picker.min.js"></script>

<script>
    // 点击图片等于点击上传框
    $('#img').click(function() {
        $('#avatar').click();
    });

    // 监听上传框的值有变化时触发事件
    $('#avatar').change(function() {
        let file = $(this)[0].files[0];


        if (file) {
            // 创建一个FileReader对象,
            // 该对象是用来读取文件中的数据的
            let Reader = new FileReader();
            // 读取文件中的数据,方法会将文件转换为DataURL格式，这是一种将文件内容编码为URL的字符串表示形式的方法。
            Reader.readAsDataURL(file);

            // 读取操作完成后会触发onload事件（当reader加载完，触发事件）
            Reader.onload = function() {
                $('#img').attr('src', Reader.result);
            }

        }
    });



    // 查询部门
    // $('#depid').change(function(){

    // })

    // (function() {
    //     $.ajax({
    //         type: 'post',
    //         url: 'api.php',
    //         data: {
    //             action: 'depid'
    //         },
    //         dataType: 'json',
    //         success: function(res) {
    //             if (res.code === 1) {

    //                 let temp = '';

    //                 for (let item of res.data) {
    //                     temp += `<option value="${item.id}">${item.name}</option>`
    //                 }

    //                 $('#depid').html(temp);

    //                 let depid = res.data[0].id ? res.data[0].id : '';

    //                 getjobData(depid);
    //             }
    //         }
    //     });
    // })();

    function getjobData(depid) {
        $.ajax({
            type: 'post',
            url: 'api.php',
            data: {
                action: 'jobid',
                depid
            },
            dataType: 'json',
            success: function(res) {
                if (res.code === 1) {

                    let temp = '';

                    for (let item of res.data) {
                        temp += `<option value="${item.id}">${item.name}</option>`
                    }
                    $('#jobid').html(temp);
                }
            }
        });
    };

    // 选择部门时更新
    $('#depid').change(function() {
        let depid = $(this).val();
        getjobData(depid);
    });

    // 选择地区
    $("#region").on("cp:updated", function() {
        var citypicker = $(this).data("citypicker");
        var code = citypicker.getCode("district") || citypicker.getCode("city") || citypicker.getCode("province");
        $("#code").val(code);
    });
</script>